<?php

$ip = $_SERVER['REMOTE_ADDR'];
$test = explode('.',$ip);
$loc =  range(17,32);

if ($test[0] == '192' || $test[0] == '10' || $ip = '127.0.0.1' || $test[0] == '172' && in_array($test[1],$loc)) {	
	include_once(getcwd().'/includes/functions.php');

	if (isset($_GET['config']) && $_GET['config'] == 'true') {
		include_once(getcwd().'/includes/connection.php');

		if (isset($_GET['getfolders']) && $_GET['getfolders'] == 'true') {
			try {
				$result = "SELECT * FROM config ORDER BY id ASC";				
				foreach($sonic->query($result) as $row) {
					if($row['music'] != true) {
						$row['music'] = 'false';
					}
					if($row['video'] != true) {
						$row['video'] = 'false';
					}
					$video = trim($row['video']);
					$music = trim($row['music']);
					echo $music." ".$video." ";
				}
			}
			catch(PDOException $e) {
				echo $e->getMessage();
				die;
			}
			die;
		} else {
			try {
				$music = 'false';
				$video = 'false';				
				if(isset($_GET['music']) && $_GET['music']  == 'true') {
					$music = 'true';
					$music = trim($music);
				} 
				else if(isset($_GET['video']) && $_GET['video'] == 'true') {
					$video = 'true';
					$video = trim($video);
				}
				$folder = trim($_GET['folder']);
				$result = "UPDATE config SET music = '{$music}', video = '{$video}' WHERE id = '{$folder}'";
				$sonic->exec($result);
			}
			catch(PDOException $e) {
				echo $e->getMessage();
				die;
			}
			die;
		}
		die;
	} 
	else if(isset($_GET['setup']) && $_GET['setup'] == 'true') {
		$sFile = getcwd().'/includes/settings.php';
		$fh = fopen($sFile,'w') or die("Can't open file");
		$data = "<?php\n";
		fwrite($fh,$data);
		$db_type = $_GET['db_type'];
		$data = "define('DB_TYPE','$db_type');\n";
		fwrite($fh,$data);
		$server = $_GET['server'];
		if($server[strlen($server)-1] == chr(47)) {
			$data = "define('SERVER','$server');\n";
		}
		else { 
			$server = $server.chr(47);
			$data = "define('SERVER','$server');\n";
		}
		fwrite($fh,$data);
		$jukebox = $_GET['juke'];
		if($jukebox[strlen($jukebox)-1] == chr(47)) {
			$data = "define('JUKE','$jukebox');\n";
		}
		else {
			$jukebox = $jukebox.chr(47);
			$data = "define('JUKE','$jukebox');\n";
		}
		fwrite($fh,$data);
		$s_user = $_GET['s_user'];
		$s_pass = $_GET['s_pass'];
		$data = "define('CREDS','u=$s_user&p=$s_pass&v=1.2.0&c=bologna');\n";
		fwrite($fh,$data);
		if ($db_type == 'mysql') {	
			$db_server = $_GET['db_server'];
			$data = "define('DB_SERVER','$db_server');\n";
			fwrite($fh,$data);
			$db_user = $_GET['db_user'];
			$data = "define('DB_USER','$db_user');\n";
			fwrite($fh,$data);
			$db_name = $_GET['db_name'];
			$data = "define('DB_NAME','$db_name');\n";
			fwrite($fh,$data);
			$db_pass = $_GET['db_pass'];
			$data = "define('DB_PASS','$db_pass');\n";
			fwrite($fh,$data);
		}
		$data = "?>";
		fwrite($fh,$data);
		die;	
		
	} 
	else if (isset($_GET['scanfolders']) && $_GET['scanfolders'] == 'true') {
		try {
			include_once(getcwd().'/includes/connection.php');
			if(DB_TYPE == 'sqlite') {
				$result = $sonic->exec("SELECT * FROM config");
				$result = $sonic->exec("DELETE FROM config");
			}
			else { $result = $sonic->exec("TRUNCATE config"); }
			$file = JUKE."rest/getMusicFolders.view?".CREDS;
			$arr = my_xml2array($file);
			$i=0;
			while ($i<count($arr[0][0])-1)  {	
				$id = $arr[0][0][$i]['attributes']['id'];
				$result = "INSERT INTO config (id) VALUES('{$id}')";
				$sonic->exec($result);
				$i++;
			}
		}
		catch(PDOException $e) {
				echo $e->getMessage();
				die;
		}
		die;
	} 
	else if (isset($_GET['rescan']) && $_GET['rescan'] == 'true') {
		include_once(getcwd().'/includes/settings.php');
		include_once(getcwd().'/includes/connection.php');
		$file = JUKE."rest/getMusicFolders.view?".CREDS;
		$arr = my_xml2array($file);
		$i=0;
		while ($i<count($arr[0][0])-1)  {
			$id = $arr[0][0][$i]['attributes']['id'];
			$name = $arr[0][0][$i]['attributes']['name'];
			echo	"<div style='margin:3px; width:350px;'>
						<div style='float:left; width:155px;' class='musicfolderid'>$name($id)</div>
						<div style='float:right;'>
							<input name='type$i' type='radio' class='music'>Music</input>
							<input name='type$i' type='radio' class='video'>Video</input>
						</div>
					</div>";
			$i++;
		}
		die;
	} 
	else if (isset($_GET['createtable']) && $_GET['createtable'] == 'true') {
		include_once(getcwd().'/includes/settings.php');
		try {
			if (DB_TYPE == 'sqlite') {	
				if (is_file(getcwd()."/db/mp3.sqlite")) {
					unlink(getcwd()."/db/mp3.sqlite");
				}
				$sonic = new PDO("sqlite:".getcwd()."/db/mp3.sqlite");
			} 
			else {
				$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
				$result3 = mysql_query("CREATE DATABASE ".DB_NAME);
				mysql_close($connection);
				$dsn = 'mysql:dbname='.DB_NAME.';host='.DB_SERVER;
				$user = DB_USER;
				$password = DB_PASS;
				$sonic = new PDO($dsn, $user, $password);
			} 
			$sonic->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);			
			$username = trim($_GET['username']);
			$password = trim($_GET['password']);
			$hashed_password = sha1($password);
			$sql = "CREATE TABLE users (
				id INTEGER NOT NULL PRIMARY KEY,
				username TEXT DEFAULT NULL,
				hashed_password TEXT DEFAULT NULL,
				shuffle INTEGER DEFAULT '0',
				timestamp INTEGER DEFAULT '1',
				reap INTEGER DEFAULT '0',
				current TEXT NOT NULL DEFAULT '',
				currentsong TEXT NOT NULL DEFAULT '',
				currentid TEXT NOT NULL DEFAULT '',
				duration TEXT NOT NULL DEFAULT '',
				cover TEXT NOT NULL DEFAULT '',
				admin INTEGER NOT NULL DEFAULT '0'				
			)";
			$result = $sonic->exec($sql);
			$sql1 = "CREATE TABLE config (
				id INTEGER NOT NULL PRIMARY KEY,
				music TEXT NOT NULL DEFAULT '',
				video TEXT NOT NULL DEFAULT ''
			)";
			$result1 = $sonic->exec($sql1);
			$sql2 = "INSERT INTO users (
				username, hashed_password,admin
			) VALUES (
				'{$username}', '{$hashed_password}','1'
			)";
			$result2 = $sonic->exec($sql2);
			$file = JUKE."rest/getMusicFolders.view?".CREDS;
			$arr = my_xml2array($file);
			$i=0;
			while ($i<count($arr[0][0])-1)  {	
				$id = $arr[0][0][$i]['attributes']['id'];
				$sql4 = "INSERT into config (id) VALUES ('{$id}')";
				$sonic->exec($sql4);
				$i++;
			}
			die;
		}
		catch(PDOException $e) {
			echo $e->getMessage();
			die;
		}
	}
	echo	"<html>
				<head>
					<title>Supersonic Setup</title>
					<link type='text/css' href='css/setup.css' rel='stylesheet' />
					<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
					<link type='text/css' href='css/custom-theme/jquery-ui-1.8.2.custom.css' rel='stylesheet' />	
					<script type='text/javascript' src='js/jquery-ui-1.8.2.custom.min.js'></script>
					<script type='text/javascript' src='js/setup.js'></script>
				</head>
				<body color='#fff' bgcolor='#000'>
					<div id='hint'></div>
					<div id='container'>
						<div id='menu'>
							<span style='display:inline; font-size:20px; float:left;'>
								<img src='img/subsonic.png' />
								<span style='position:relative; font-size:20px; top:-8px;'> Setup</span>
							</span>
							<button id='foldersetup'>3. configure folders</button>
							<button id='createtable'>2. create db/tables</button>
							<button id='setup'>1. run basic setup</button>
	
						</div>
						<div id='main'>";
	
	if (is_file(getcwd().'/includes/settings.php')) {        
		include_once(getcwd().'/includes/settings.php');

		if (SERVER == '' || JUKE == '' || CREDS == '') {
			// Security hole in javascript
			echo	"<script type='text/javascript'>\n
						function fillConfig() {
							$('#juke').val('".JUKE."');\n
							$('#server').val('".SERVER."');\n
						}\n
						
						$(document).ready(function() {\n
							$('#status').html(\"There seems to be an issue with some variables, please rerun basic setup.\");\n
							$('#hint').position({ my:'left top',at:'left bottom',of:'#setup',offset:'0 5' }).css('width','112px');\n
						});\n
					</script>";
		} 
		else {
			require_once(getcwd()."/includes/settings.php");	
			if ((!defined('SERVER')) || SERVER == '' || (!defined('JUKE')) || JUKE == '' || (!defined('CREDS')) || CREDS == '') {
				echo 'There seems to be an issue with some variables, please rerun basic <a href=\'setup.php\'>setup</a>';
				die;
			}
			if (DB_TYPE == 'sqlite') { //connect/create the sqlite db
				try {
					$sonic = new PDO("sqlite:".getcwd()."/db/mp3.sqlite");
					$sonic->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
					$qry = "SELECT * from users";
					$result = $sonic->query($qry);
					echo	"<img src='img/check.gif' />
							Connected to db, users table exists.
							<br />
							<script type='text/javascript'>
								$(document).ready(function() {
									$('#hint').position({my:'left top', at:'left bottom', of:'#foldersetup', offset:'1 3', collision:'fit'});\n
								});\n
							</script>";
					} 
					catch (PDOException $e) {
						echo	"<img src='img/x.gif' />
							Connected to db, but users table not created. Hit 'create db/tables' above ^
							<br />
							<script type='text/javascript'>
								$(document).ready(function() {
									$('#hint').position({my:'left top',at:'left bottom', of:'#createtable', offset:'0 3',collision:'fit'});\n
								});\n
							</script>";
					}
			}
			else if (DB_TYPE == 'mysql') { //connect to the mysql db
				if (!defined('DB_NAME') || DB_NAME == '' || !defined('DB_USER') || DB_USER == '' || !defined('DB_PASS') || DB_PASS == '' || !defined('DB_SERVER') || DB_SERVER == '') {
					echo	"There seems to be an issue with some variables, please rerun basic <a href='setup.php'>setup</a>";
					die;
				}
				else { // 1. Create a database connection
					$dsn = 'mysql:dbname='.DB_NAME.';host='.DB_SERVER;
					$user = DB_USER;
					$password = DB_PASS;
					try {
						$sonic = new PDO($dsn, $user, $password);
						$qry = "SELECT * from users";
						$result = $sonic->query($qry);
						echo	"<img src='img/check.gif' />
							Connected to db, users table exists.
							<br />
							<script type='text/javascript'>
								$(document).ready(function() {
									$('#hint').position({my:'left top', at:'left bottom', of:'#foldersetup', offset:'1 3', collision:'fit'});\n
								});\n
							</script>";
					} 
					catch (PDOException $e) {
						echo	"<img src='img/x.gif' />
							Connected to db, but users table not created. Hit 'create db/tables' above ^
							<br />
							<script type='text/javascript'>
								$(document).ready(function() {
									$('#hint').position({my:'left top',at:'left bottom', of:'#createtable', offset:'0 3',collision:'fit'});\n
								});\n
							</script>";
					}
				}
			}
			$file = JUKE."rest/ping.view?".CREDS;
			$arr = my_xml2array($file);
		
			if($arr[0]['attributes']['status'] == 'ok') {
				echo	"<img src='img/check.gif' /> Connection to Subsonic server OK<hr size='1' />";
			} 
			else {
				echo	"<img src='img/x.gif' /> Connection to Subsonic server failed. ";
			}
		
			echo	"Local server ip/port:".SERVER."<br />
				Subsonic server/port:".JUKE."<br />
				<hr size='1'>";
			
			if (DB_TYPE == 'mysql') {
				echo	"Database name:".DB_NAME."<br />
					Database username:".DB_USER."<br />
					Database password:".DB_PASS."<br />
					<hr size='1'>";
			}
			$a = explode('&', CREDS);
			$i = 0;
			while ($i < count($a)) {
				$b = explode('=', $a[$i]);
				switch($i) {
					case 0: {
						$username = $b[1];
						echo "Subsonic username:".htmlspecialchars(urldecode($b[1]))."<br />";
						break;
					}
					case 1: {
						$password = $b[1];
						echo "Subsonic password:".htmlspecialchars(urldecode($b[1]))."<br />";
						break;						
					}
					case 2: {
						echo "API Version:".htmlspecialchars(urldecode($b[1]))."<br />";
						break;
					}
					case 3: {
						echo "Player name:".htmlspecialchars(urldecode($b[1]))."<br />";
						break;
					}
				}
				$i++;
			}

			if ($username != '' && $password != '' && defined('SERVER') && defined('JUKE') && defined('CREDS')) {
				echo	"<script type='text/javascript'>\n
							function fillConfig() {
								$('#juke').val('".JUKE."');\n
								$('#server').val('".SERVER."');\n
							}\n
							
							$(document).ready(function() {\n
								$('#status').append(\"<span>Script variables look setup, create the database if you haven't already, then configure your music/video folders\");\n								
							});\n
						</script>";
			} 
			else {
				echo	"<script type='text/javascript'>\n
							function fillConfig() {
								$('#juke').val('".JUKE."');\n
								$('#server').val('".SERVER."');\n
							}\n
							
							$(document).ready(function() {\n
								$('#status').html(\"There seems to be an issue with some variables, please rerun basic setup.\");\n
							});\n
						</script>";
				}
			}
		
	}
	else {
		if (method_exists('PDO','getAvailableDrivers')) {
			echo	"<img src='img/check.gif' /> PDO is installed<br />"; 
			foreach(PDO::getAvailableDrivers() as $instance) {
				echo ' - '.$instance.' extension available<br />';
			}
		}
		else {
			echo	"<img src='img/x.gif' /> PDO is not installed, please enable the extension or compile it in. </br>";
		}
		if (function_exists('curl_init')) {
			echo	"<br /><img src='img/check.gif' /> cURL is installed<br />"; 
		}
		else { 
			echo	"<br /><img src='img/x.gif' /> cURL extension is not enabled, DI.fm streams will not work<br />";  
		}
		echo	"<br />Settings.php not found, please run basic setup.
				<script type='text/javascript'>
					$(document).ready(function() {
						$('#hint').position({ my:'left top',at:'left bottom',of:'#setup',offset:'0 5' }).css('width','112px');\n
					});\n
				</script>";
	}

	echo	"</div>
			<div id='status'></div>";
	
	echo	"<div id='foldersetupd'>
			<div id='folders'>";

	$file = JUKE."rest/getMusicFolders.view?".CREDS;
	$arr = my_xml2array($file);
	$i=0;
	
	while ($i<count($arr[0][0])-1)  {
		$id = $arr[0][0][$i]['attributes']['id'];
		$name = $arr[0][0][$i]['attributes']['name'];
		
		echo	"<div style='margin:3px; padding:1px; width:350px;'>
					<div style='float:left; width:300px;' class='musicfolderid' id='$id'>$name($id)
						<div style='float:right;'>
							<input name='type$id' type='radio' class='music'>Music</input>
							<input name='type$id' type='radio' class='video'>Video</input>
						</div>
					</div>
				</div>";

		$i++;
	}
	
	echo	"</div>
			</div>
			<div id='warn'>This will delete all user logins, preferences, and folder configs for the frontend
				<div class='line'><label for='a_user'>Admin Username</label><input type='text' id='a_user' /></div>
				<div class='line'><label for='a_pass'>Admin Pass</label><input type='password' id='a_pass' /></div>
			</div>";

	echo	"<div id='setupd'>
				<div><form id='bla'>
					MySQL <input checked='checked' id='mysql' type='radio' name='db_type'></input>
					 SQLite <input id='sqlite' type='radio' name='db_type'></input>
				</form></div><br />
				<div id='fields'>
					<div class='line'>
						<div class='text'>Server (ex> http://ip:port/)</div>
						<input type='text' id='server' value='http://' />
					</div>
					<div class='line'>
						<div class='text'>Subsonic server (ex> http://ip:port/)</div>
						<input type='text' id='juke' value='http://' />
					</div>
					<div class='line'>
						<div class='text'>Subsonic username</div>
						<input type='text' id='s_user' />
					</div>
					<div class='line'>
						<div class='text'>Subsonic password</div>
						<input type='password' id='s_pass' />
					</div>
					<div class='mysqlopts'>
					<div class='line'>
					<div class='text'>DB Server</div>
					<input type='text' id='db_server' />
				</div>
					<div class='line'>
					<div class='text'>Database name</div>
					<input type='text' id='db_name' />
				</div>
				<div class='line'>
					<div class='text'>Database user</div>
					<input type='text' id='db_user' />
				</div>
				<div class='line'>
					<div class='text'>Database password</div>
					<input type='text' id='db_pass' />
				</div>
					</div>
			</div></div>
			
			</div>
			
			</body>
			</html>";
	
} 
else {
	die(header("Location: /"));
}
?>